package com.fly.security.handler

import com.fly.security.entity.User
import com.fly.security.service.UserService
import kotlinx.coroutines.reactive.awaitFirstOrNull
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.server.*

/**
 * @author  fly
 * @date  2021/7/29 18:12
 * @version 1.0
 */
@Component
class UserHandler {

    @Autowired
    private lateinit var userService: UserService

    suspend fun findAll(request: ServerRequest): ServerResponse = ServerResponse.ok().json().bodyAndAwait(userService.findAll())

    suspend fun saveUser(request: ServerRequest): ServerResponse = request.bodyToMono(User::class.java).awaitFirstOrNull()
        ?.run { ServerResponse.ok().json().bodyAndAwait(userService.saveUser(this)) }
        ?: ServerResponse.badRequest().json().bodyValueAndAwait("invalid body")
}